// pages/handleTask/handleTask.js
//获取应用实例 
const app = getApp();
const util = require('../../../utils/util.js');
var BLELocker = require("../../../utils/BLELocker.js");
var blueConStatHandler = require("../../../utils/blueConStatHandler.js");
const lbbService = require('../../../pages/service/service.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        hospitalName: '',
        endTime: '',
        InspectionNumber: '100',
        taskNumber: '20',
        btnShow: 'true',
        background: "#f2f2f2",
        sidebarShow: null,
        activeKey: 0,
        active: 0,
        confirShow: false,
        taskId: null,
        scrollHeight: 450,
        loading_show: false,
        isnoData: false,
        temporaryTasks: '0',
        longTask: '0',
        showFrom: false,
        textArea: null,
        showPrompt:false,
        imgArrays: [],
        antennaList: [],
        boxList: [],
        equList: [],
        gatewayList: [],
        screwList: [],
        maintenancetasks: [],
        longTaskList: [],
        modal_show: {
            modal_show: false,
            confirm: false,
            retryConnect: false,
            retry95: false,
        },
        isConnecting: false,
        content: {
            gateway: [{
                taskname: '网关充电',
                list: [{
                        num: "2158555",
                        id: 0
                    },
                    {
                        num: "2158555",
                        id: 0
                    },
                    {
                        num: "2158555",
                        id: 1
                    },
                ]
            }],

        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        if (options.activeKey == '3') {
            that.setData({
                active: 1
            })
        }
        that.setData({
            endTime: options.time,
            hospitalName: options.hospitalName,
            userId: options.userId,
            hospitalId: options.hospitalId,
            btnShow: options.btnShow,
            sidebarShow: options.activeKey,
            taskType: options.taskType,
        })
        that.getLongTaskList()
        that.getTaskListNumber()
        that.getTemporaryTaskList()
        console.log("==)", options)

    },

    //获取运维长期任务列表
    getLongTaskList() {
        let that = this
        lbbService.getLongTaskList({
            userId: that.data.userId,
            hid: that.data.hospitalId,
            time: that.data.endTime,
            isHandle: that.data.active,
            taskType: that.data.taskType
        }, function (res) {
            console.log('长期', res.data)
            res.data.forEach(item=>{
                item.tempTaskList.forEach(itm=>{
                    if(itm.taskImages){
                        itm.taskImages=itm.taskImages.split(',')
                    }
                })
            })
            that.setData({
                longTaskList: res.data
            })
        })
    },
    //获取运维临时任务
    getTemporaryTaskList() {
        let that = this
        lbbService.getTemporaryTaskList({
            userId: that.data.userId,
            hid: that.data.hospitalId,
            time: that.data.endTime,
            isHandle: that.data.active,
            taskType: that.data.taskType
        }, function (res) {
            for (let i = 0; i < res.data.records.length; i++) {
                if (res.data.records[i].taskImages) {
                    res.data.records[i].taskImages = res.data.records[i].taskImages.split(',')
                }
                if (res.data.records[i].endTime) {
                    if (res.data.records[i].endTime.split(' ')[0] > res.data.records[i].handleRuleTime) {
                        res.data.records[i]['state'] = '逾期完成'
                    } else {
                        res.data.records[i]['state'] = '已完成'
                    }
                }
            }
            that.setData({
                maintenancetasks: res.data.records,
            })
        })
    },
    //获取医院任务数量
    getTaskListNumber() {
        let that = this
        if (that.data.activeKey == '0') {
            lbbService.getTaskListNumber({
                userId: that.data.userId,
                taskType: that.data.taskType,
                hid: that.data.hospitalId,
                time: that.data.endTime,
                type: that.data.activeKey == '0' ? '1' : '0'
            }, function (res) {
                that.setData({
                    taskDevOpsCount: res.data.noHandleCount,
                    noHandleCount: res.data.noHandleCount,
                    handleCount: res.data.handleCount,
                    temporaryTasks: res.data.handleCount
                })
                that.DisplayData()
            })
            lbbService.getTaskListNumber({
                userId: that.data.userId,
                taskType: that.data.taskType,
                hid: that.data.hospitalId,
                time: that.data.endTime,
                type: that.data.activeKey == '0' ? '0' : '1'
            }, function (res) {
                that.setData({
                    longTask: res.data.handleCount,
                    taskLongDevOpsCount: res.data.noHandleCount,
                })
            })
        } else if (that.data.activeKey == '1') {
            lbbService.getTaskListNumber({
                userId: that.data.userId,
                taskType: that.data.taskType,
                hid: that.data.hospitalId,
                time: that.data.endTime,
                type: that.data.activeKey == '0' ? '1' : '0'
            }, function (res) {
                that.setData({
                    taskLongDevOpsCount: res.data.noHandleCount,
                    noHandleCount: res.data.noHandleCount,
                    handleCount: res.data.handleCount,
                    longTask: res.data.handleCount
                })
                that.DisplayData()
            })
            lbbService.getTaskListNumber({
                userId: that.data.userId,
                taskType: that.data.taskType,
                hid: that.data.hospitalId,
                time: that.data.endTime,
                type: that.data.activeKey == '0' ? '0' : '1'
            }, function (res) {
                that.setData({
                    temporaryTasks: res.data.handleCount,
                    taskDevOpsCount: res.data.noHandleCount,
                })
            })
        }

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let that = this
    },
    DisplayData() {
        let that = this
        if (that.data.active == '0' && that.data.noHandleCount == 0) {
            that.setData({
                isnoData: true
            })
        } else if (that.data.active == '0' && that.data.noHandleCount != 0) {
            that.setData({
                isnoData: false
            })
        } else if (that.data.active == '1' && that.data.handleCount == 0) {
            that.setData({
                isnoData: true
            })
        } else if (that.data.active == '1' && that.data.handleCount != 0) {
            that.setData({
                isnoData: false
            })
        }
    },
    //切换侧边栏
    changeStat(e) {
        let that = this
        that.setData({
            activeKey: e.detail
        })
        that.getTaskListNumber()
        if (e.detail == '1') {
            that.getLongTaskList()
        } else if (e.detail == '0') {
            that.getTemporaryTaskList()
        }
    },
    tabChange(e) {
        let that = this
        this.setData({
            active: e.detail.index
        })
        if (that.data.activeKey == '1') {
            that.getLongTaskList()
        } else if (that.data.activeKey == '0') {
            that.getTemporaryTaskList()
        }
        that.DisplayData()
    },
    //点击完成
    tocomplete: function (e) {
        let that = this
        that.location(0, e)
    },
    //获取当前位置
    location: function (e, data) {
        let that = this
        // wx.getLocation({
        //     type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        //     success (res) {
        //         console.log('获取经纬度成功', res,app)
        //         that.setData({
        //             latitude:res.latitude,
        //             longitude:res.longitude
        //         })
        //         that.getAddress(e,data);
        //     },fail: function (res) {
        //         that.getAddress(e,data);
        //       }
        //    })
        that.getWXLocation(that, e, data)
    },
    //每次点击都获取当前位置
    getWXLocation: (thats, e, data) => {
        wx.showLoading({
            title: '定位中...',
            mask: true,
        })
        return new Promise((resolve, reject) => {
            let _locationChangeFn = (res) => {
                resolve(res);
                thats.setData({
                    latitude: res.latitude,
                    longitude: res.longitude
                })
                thats.getAddress(e, data)
                wx.hideLoading()
                wx.offLocationChangeError(_locationChangeFn)
                wx.offLocationChange(_locationChangeFn)
                wx.stopLocationUpdate()
            }
            wx.startLocationUpdate({
                success: (res) => {
                    wx.onLocationChangeError(_locationChangeFn)
                    wx.onLocationChange(_locationChangeFn)
                },
                fail: (err) => {
                    wx.hideLoading()
                    reject()
                    thats.getAddress(e, data)
                }
            })
        })
    },
    getAddress: function (e, data) {
        let that = this
        wx.request({
            url: 'https://api.map.baidu.com/geocoder/v2/',
            method: 'GET',
            data: {
                location: that.data.latitude + ',' + that.data.longitude,
                output: 'json',
                coordtype: 'wgs84ll',
                pois: 1,
                s: 1,
                latest_admin: 1,
                ak: 'GQKwKHdtu8CgmxXIkXdyTkdtlfvML4Gg'
            },
            success(res) {
                console.log('>>', res)
                if (res.data.status == 0 && res.data.result.formatted_address) {
                    let address = res.data.result.formatted_address
                    that.setData({
                        address: address,
                    })
                    if (e == 1) {
                        that.setData({
                            showFrom: true,
                        })
                    } else if (e == 0) {
                            wx.showModal({
                            title: '完成',
                            content: `您确定完成${data.currentTarget.dataset.name}吗？`,
                            showCancel: true,
                            confirmText: '确定',
                            success(res) {
                                if (res.confirm) {
                                    lbbService.TaskItemsOk({
                                        taskLongStateId: data.currentTarget.dataset.id,
                                        handleLocation: that.data.address
                                    }, function (res) {
                                        console.log(res)
                                        that.getLongTaskList()
                                        that.getTaskListNumber()
                                    })
                                }
                            }
                        }) 
                    }      
                } else {
                    wx.showToast({
                        title: '获取位置失败,请打开手机定位重新定位',
                        icon: 'none',
                        duration: 3000
                    })
                    that.setData({
                        address: null,
                    })
                }
            },
            fail() {
                that.setData({
                    address: null,
                })
            }
        })
    },
    //点击已充电
    Charged(e) {
        let that = this
        wx.showModal({
            title: '已充电',
            content: '确定已完成网关充电吗？',
            showCancel: true,
            confirmText: '确定',
            success(res) {
                if (res.confirm) {
                    console.log(e.currentTarget.dataset)
                    lbbService.ChargedOk({
                        taskLongDetailId: e.currentTarget.dataset.id
                    }, function (res) {
                        that.getLongTaskList()
                        that.getTaskListNumber()
                    })
                }
            }
        })
    },
    //去处理
    goHandle: function (e) {
        let that = this
        that.location(1, undefined)
        that.setData({
            taskId: e.currentTarget.dataset.id
        })
    },
    // 输入框内容
    bindAreaChange(e) {
        let that = this
        that.setData({
            textArea: e.detail.value ? e.detail.value : ''
        })
    },
    // 输入框确定按钮
    okRemarks() {
        let that = this
        console.log(this.data.textArea, that.data.taskId)
        lbbService.HandleOk({
            taskDevOpsId: that.data.taskId,
            handleDesc: that.data.textArea ? that.data.textArea : '',
            handleLocation: that.data.address
        }, function (res) {
            that.getTemporaryTaskList()
            that.getTaskListNumber()
            that.setData({
                textArea: null,
                showFrom: false
            })
        })
    },
    // 输入框取消按钮
    cancel() {
        this.setData({
            showFrom: false,
            textArea: null,
        })
    },
    //周期任务设备拍照完成
    okLongTask(e){
        let that=this
        lbbService.TaskItemsOk({
            taskLongStateId: e.currentTarget.dataset.longtaskid,
            handleLocation: that.data.address
        }, function (res) {
            console.log(res)
            that.getLongTaskList()
            that.getTaskListNumber()
        })
    },
    //预览图片
    preViewImgs(e) {
        let current = e.currentTarget.dataset.current
        let urls = e.currentTarget.dataset.imglist
        util.previewImgs(current, urls);
    },

    //开锁
    unlock(e) {
        let that = this
        wx.navigateTo({
            url: '../../../pages/startPatrol/startPatrol?hospitalId=' + that.data.hospitalId + '&hospitalName=' + that.data.hospitalName,
        })
    },
    //添加反馈
    addFeedback() {
        let that = this
        wx.navigateTo({
            url: '../../../pages/startPatrol/startPatrol?hospitalId=' + that.data.hospitalId + '&hospitalName=' + that.data.hospitalName,
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        BLELocker.disconnect();
        this.hideModal1();
    },

    //新增桩位和设备的回调
    newEquip: function () {
        let that = this;
        that.data.isConnecting = false;
        let data = that.data.data_95;
        if (data) {
            let pileCode = that.data.pileCode
            let hospitalId = that.data.hospitalId
            let hospitalName = that.data.hospitalInfo.basicInfo.hospitalName
            let feeRules = JSON.stringify(that.data.hospitalInfo.basicInfo.feeRules)
            if (data.rfid.indexOf('FF') != -1) {
                wx.navigateTo({
                    url: '/pages/newEquipment/newEquipment?hospitalId=' + hospitalId + '&hospitalName=' + hospitalName + '&pileCode=' + pileCode + '&feeRules=' + feeRules,
                })
            } else {
                lbbService.queryEquipByRfid({
                    rfid: data.rfid
                }, function (res) {
                    console.log("通过rfid获取到的信息>>", res)
                    let equipCode = res.equipmentId
                    let equipType = res.categoryName
                    let eqtModelName = res.eqtModelName
                    wx.navigateTo({
                        url: '/pages/newEquipment/newEquipment?equipCode=' + equipCode + '&equipType=' + equipType + '&hospitalId=' + hospitalId + '&hospitalName=' + hospitalName + '&pileCode=' + pileCode + '&eqtModelName=' + eqtModelName + '&feeRules=' + feeRules,
                    })
                })
            }
        }
    },
    //新增桩位和设备
    scan: function () {
        let that = this
        that.getLocation(that.scanCallback)
    },
    scanCallback: function () {
        let that = this
        that.setData({
            isScanning: true
        })
        wx.scanCode({
            success(res) {
                var qrc = '';
                if (res.result.indexOf(util.CONST_DATA.DEVICE_QRCODE_URL_PREFIX) == 0) {
                    var rst = res.result.split('/');
                    qrc = rst[rst.length - 1];
                    that.data.scan_qrc = qrc;
                } else {
                    var str = res.result.split(':')
                    var strn = ''
                    str.forEach(item => {
                        return strn += item
                    })
                    that.data.scan_qrc = strn;
                }
                that.data.isConnecting = true;
                lbbService.getMacId({
                    markCode: that.data.scan_qrc,
                    system: getApp().globalData.systemInfo ? getApp().globalData.systemInfo.system : 'ios'
                }, function (res) {
                    if (res.macId) {
                        that.data.newConFlg = res.newConFlg;
                        that.data.curIsDirectCon = res.curIsDirectCon;
                        that.data.pileCode = res.pileId;
                        that.data.macId = res.macId;
                        that.data.wxDeviceId = getApp().getDeviceId(res.macId);
                        that.getConnect(res.macId);
                    } else {
                        that.data.isConnecting = false;
                        that.toast.showToast('获取mac失败');
                    }
                })
            },
            complete(res) {
                that.setData({
                    isScanning: false
                })
            }
        })
    },
    // 设备数组中转
    setOtherEquipmentList(equList) {
        console.log('我有没有执行')
        var that = this
        var arr = []
        var otherList = []
        var arrB
        let otherEquList = !equList ? that.data.hospitalInfo.otherEquList : equList;
        otherEquList.forEach((item) => {
            arr.push(item.equipName)
        })
        var arrA = new Set(arr)
        console.log(arrA)
        arrB = [...arrA]
        console.log('我有没有执行A', arrB)
        arrB.forEach((item) => {
            var list = []
            otherEquList.forEach((item1) => {
                if (item == item1.equipName) {
                    list.push(item1)
                }
            })
            otherList.push({
                title: item,
                dataList: list
            })
        })
        that.setData({
            otherList: otherList
        })
        console.log('otherList:', otherList)
    },
    hideModal1() {
        this.setData({
            modal: {
                modal_show: false,
                confirm: false,
                retry95: false,
                retryConnect: false
            }
        })
    },
    /**
     * 重试95
     */
    retry95() {
        let that = this;
        that.hideModal1();
        that.setData({
            loading_show: true,
            loading_desc: "数据读取中"
        });
        BLELocker.send95Command(function (isSuccess) {
            if (isSuccess == false) {
                that.getConnect(that.data.macId)
            } else {}
        })
    },
    /**
     * 重试蓝牙连接
     */
    retryConnect() {
        console.log('retryConnect');
        let that = this;
        that.hideModal1();
        that.getConnect(that.data.macId);
    },
    getConnect: function (macId) {
        let that = this
        that.setData({
            loading_show: true,
            loading_desc: "设备连接中"
        });
        if (that.data.newConFlg) {
            BLELocker.newConnect('DK' + macId, function (status, data) {
                blueConStatHandler.handleStatus(status, data, that, that.newEquip, true)
            }, 0, false, null, null, that);
        } else {
            BLELocker.directConnect('DK' + macId, function (status, data) {
                blueConStatHandler.handleStatus(status, data, that, that.newEquip, true)
            }, 0, false, null, null, that);
        }
    },
    getLocation: function (_callback) {
        wx.getLocation({
            type: 'wgs84',
            success: function (res) {
                console.log('获取经纬度成功', res)
                app.globalData.header.lat = parseFloat(res.latitude)
                app.globalData.header.lng = parseFloat(res.longitude)
                if (!app.globalData.header.lng) {
                    wx.showToast({
                        title: '请打开定位',
                        image: '/images/gantan.png',
                    })
                    setTimeout(function () {
                        wx.navigateTo({
                            url: '../../../pages/toAuth/toAuth',
                        })
                        return
                    }, 1000)
                } else if (_callback) {
                    _callback()
                }
            },
            fail: function (res) {
                console.log('获取经纬度fail', res)
                wx.showToast({
                    title: '请打开定位',
                    image: '/images/gantan.png'
                })
                setTimeout(function () {
                    wx.navigateTo({
                        url: '../toAuth/toAuth',
                    })
                    return
                }, 1000)
            }
        })
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('返回')
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})